import { Platform } from 'react-native';
import { acknowledgePurchaseAndroid, finishTransaction, getAvailablePurchases } from 'react-native-iap';

import axios from 'axios';
import { Purchase } from 'react-native-iap/src/types';
import { Product, Subscription } from 'react-native-iap/src/types';

import map from '../config/map.json';
import { PaymentSDK } from '../core/PaymentSDK';
import { PaymentConfig, CreateOrderParams, PurchaseParams, PaymentResult, OrderResult } from '../types';

export class PaymentService {
  private sdk: PaymentSDK;
  private config: PaymentConfig;
  private platform: 'ios' | 'android';

  private constructor(sdk: PaymentSDK, config: PaymentConfig) {
    this.sdk = sdk;
    this.config = config;
    this.platform = Platform.OS as 'ios' | 'android';
  }

  /**
   * 创建PaymentService实例
   * @example
   * const paymentService = await PaymentService.createInstance({
   *   api: {
   *     ios: {
   *       createOrder: iosAPI.createOrder,
   *       verifyPurchase: iosAPI.verifyPurchase,
   *       restoreSubscription: iosAPI.restoreSubscription,
   *     },
   *     android: {
   *       createOrder: androidAPI.createOrder,
   *       verifyPurchase: androidAPI.verifyPurchase,
   *       restoreSubscription: androidAPI.restoreSubscription,
   *     }
   *   },
   *   options: {
   *     environment: __DEV__ ? 'test' : 'prod',
   *     appName: 'YourAppName'
   *   }
   * });
   */
  static async createInstance(config: PaymentConfig): Promise<PaymentService> {
    const sdk = await PaymentSDK.getInstance();
    return new PaymentService(sdk, config);
  }

  /**
   * 获取android或ios平台业务API配置
   * @private
   */
  private get platformAPI() {
    return this.platform === 'ios' ? this.config.api.ios : this.config.api.android;
  }

  /**
   * 创建业务支付订单
   * @param params
   */
  async createOrder(params: Omit<CreateOrderParams, 'appName'>): Promise<OrderResult> {
    const orderParams = {
      ...params,
      appName: this.config.options.appName,
      payMethod: this.platform === 'ios' ? ('1' as const) : ('2' as const),
    };

    const result = await this.platformAPI.createOrder(orderParams);
    // Convert the Payment.PaymentResult to OrderResult
    return {
      code: result.code,
      msg: result.msg,
      data: Number(result.data), // Convert string to number
    };
  }

  /**
   * 处理业务支付：
   * 1. 先创建订单
   * 2. 拉起SDK支付界面，进行支付
   * 3. 验证支付结果
   * @param params
   */
  async handlePurchase(params: PurchaseParams): Promise<PaymentResult> {
    try {
      console.log('真实的realValue = ', params.businessProductCode);
      // 创建订单
      let order;
      try {
        order = await this.createOrder({
          payMethod: this.platform === 'ios' ? '1' : '2',
          quantity: 1,
          productCode: params.businessProductCode,
          appAccountToken: params.appAccountToken,
        });

        console.log('start======================');
        console.log('我这个order是多杀 = ', order);
        console.log('end========================');
        this.config.events?.onCreateOrderSuccess?.(order);
      } catch (error) {
        this.config.events?.onCreateOrderFailed?.(error as Error);
        throw error;
      }

      order = order.data;

      if (!order) {
        const error = new Error('Create order failed');
        this.config.events?.onCreateOrderFailed?.(error);
        throw error;
      }

      // 拉起SDK支付
      let purchase;
      try {
        purchase = await this.sdk.requestPurchase({
          product: params.product,
          skus: params.skus,
          appAccountToken: params.appAccountToken,
          orderId: order.toString(),
          userId: params.userId,
          env: params.env,
        });
      } catch (error) {
        this.config.events?.onRequestPurchaseFailed?.(error as Error);
        throw error;
      }
      if (!purchase) {
        const error = new Error('Purchase failed');
        this.config.events?.onRequestPurchaseFailed?.(error);
        throw error;
      }

      // 对于苹果支付，返回的是对象
      let currentPurchase: Purchase | undefined;
      if (!Array.isArray(purchase) && purchase.transactionId) {
        currentPurchase = purchase;
      }
      // 对于谷歌支付，返回的是数组,需要取productId对应的对象
      if (Array.isArray(purchase) && purchase?.length) {
        currentPurchase = purchase.find((item) => item.productId === params.product.productId);
      }

      if (!currentPurchase) {
        console.error('do not find currentPurchase');
        throw new Error('do not find currentPurchase');
      }
      this.config.events?.onRequestPurchaseSuccess?.(currentPurchase);

      console.log('start======================');
      console.log('支付返回的currentPurchase = ', currentPurchase);
      console.log('end========================');

      // 验证购买
      try {
        console.log('start======================');
        console.log('开始验证了');
        console.log('end========================');

        // Handle typing issues with product parameter
        const productForVerify = this.isInappProduct(params.product) ? (params.product as Product) : null;

        if (!productForVerify) {
          throw new Error('Invalid product type for verification');
        }

        const verifyResult = await this.platformAPI.verifyPurchase(
          productForVerify,
          currentPurchase,
          order as number,
          params.product.productId,
          params.businessProductCode,
        );
        console.log('start======================');
        console.log('我验证ok了');
        console.log('end========================');
        console.log({ verifyResult });
        return {
          success: true,
          data: verifyResult,
        };
      } catch (error) {
        console.error('error', error);
        throw error;
      }
    } catch (error) {
      return {
        success: false,
        error: error as Error,
      };
    }
  }

  /**
   * 恢复购买，目前仅支持ios
   */
  async restorePurchases(): Promise<PaymentResult> {
    if (!this.platformAPI?.restoreSubscription) {
      return {
        success: false,
        error: new Error('none platformAPI.restoreSubscription'),
      };
    }

    try {
      const purchases = await this.sdk.getAvailablePurchases();
      const sortedPurchases = purchases.sort((a, b) => b.transactionDate - a.transactionDate);

      if (sortedPurchases.length === 0) {
        return { success: false };
      }

      const result = await this.platformAPI.restoreSubscription(sortedPurchases[0].transactionReceipt);
      this.config.events?.onRestoreSuccess?.(result);

      return {
        success: true,
        data: result,
      };
    } catch (error) {
      this.config.events?.onRestoreFailed?.(error as Error);
      return {
        success: false,
        error: error as Error,
      };
    }
  }

  /**
   * 完成苹果支付或谷歌支付交易
   * @param purchase 购买信息
   * @param isConsumable 是否是消耗品(仅android)
   */
  async finishTransaction(
    purchase: Purchase,
    isConsumable = false,
    developerPayloadAndroid?: string,
  ): Promise<PaymentResult> {
    try {
      await this.sdk.finishTransaction(purchase, isConsumable);
      return {
        success: true,
      };
    } catch (error) {
      console.error('Failed to finish transaction:', error);
      return {
        success: false,
        error: error as Error,
      };
    }
  }

  /**
   * 判断是否是应用内商品
   */
  isInappProduct(product: Product | Subscription): product is Product {
    return this.sdk.isInappProduct(product);
  }

  /**
   * 判断是否是订阅商品
   */
  isSubscriptionProduct(product: Product | Subscription): product is Subscription {
    return this.sdk.isSubscriptionProduct(product);
  }

  /**
   * 清除交易记录
   */
  static clearTransaction() {
    return PaymentSDK.clearTransaction();
  }

  /**
   * 获取可用的购买记录
   */
  async getAvailablePurchases(): Promise<PaymentResult> {
    try {
      const purchases = await this.sdk.getAvailablePurchases();
      return {
        success: true,
        data: purchases,
      };
    } catch (error) {
      return {
        success: false,
        error: error as Error,
      };
    }
  }
}
